package com.qc.sys.service.impl;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qc.sys.common.ActiveUser;
import com.qc.sys.common.Constant;
import com.qc.sys.common.DataGridView;
import com.qc.sys.common.ResultObj;
import com.qc.sys.dao.SysRoleDao;
import com.qc.sys.dao.SysUserDao;
import com.qc.sys.entity.SysDept;
import com.qc.sys.entity.SysUser;
import com.qc.sys.service.SysDeptService;
import com.qc.sys.service.SysUserService;
import com.qc.sys.utils.AppUtils;
import com.qc.sys.utils.MD5Utils;
import com.qc.sys.vo.UserVo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * (SysUser)表服务实现类
 *
 * @author AltmanQccc
 * @since 2020-08-26 11:38:08
 */
@Service
@Transactional
@EnableCaching
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUser> implements SysUserService {

    @Autowired
    private SysUserDao userDao;

    @Autowired
    private SysRoleDao roleDao;


    private Log log= LogFactory.get(SysUserService.class);

    @Override
    public SysUser queryUserByLoginName(String loginname) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isBlank(loginname)){
            log.error("登录名不能为空");
            return null;
        }
        queryWrapper.eq("loginname",loginname);
        SysUser user = this.baseMapper.selectOne(queryWrapper);
        return user;
    }


    @Override
    public DataGridView queryAllUser(UserVo userVo) {
        IPage<SysUser> page=new Page<>(userVo.getPage(),userVo.getLimit());
        QueryWrapper<SysUser> qw=new QueryWrapper<>();
        qw.eq("type",Constant.USER_TYPE_NORMAL);
        qw.eq(null!=userVo.getDeptid(),"deptid",userVo.getDeptid());
        qw.like(StringUtils.isNotBlank(userVo.getName()),"name",userVo.getName());
        qw.like(StringUtils.isNotBlank(userVo.getAddress()),"address",userVo.getAddress());
        qw.like(StringUtils.isNotBlank(userVo.getRemark()),"remark",userVo.getRemark());
        this.userDao.selectPage(page,qw);
        List<SysUser> records = page.getRecords();
        SysDeptService deptService = AppUtils.getContext().getBean(SysDeptService.class);
        for (SysUser record : records) {
            if (null!=record.getDeptid()){
                SysDept dept = deptService.getById(record.getDeptid());
                record.setDeptname(dept.getTitle());
            }
        }
        return new DataGridView(page.getTotal(),records);
    }

    @Override
    public ResultObj InsertUser(SysUser user) {
        try {
            user.setSalt(MD5Utils.createUUID());
            user.setPwd(MD5Utils.md5(Constant.DEFAULT_PWD,user.getSalt(),2));
            user.setAvailable(Constant.USER_AVAILABLE_TRUE);
            user.setType(Constant.USER_TYPE_NORMAL);
            user.setHiredate(new Date());
            user.setImgpath(Constant.DEFAULT_IMAGE);
            this.userDao.insert(user);
            return ResultObj.ADD_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
    }

    @Override
    public ResultObj UpdateUser(SysUser user) {
        try {
            this.userDao.updateById(user);
            return ResultObj.UPDATE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
    }

    /**
     * 加载最大的排序码
     * */
    @Override
    public Integer queryUserMaxOrderNum() {
        return this.userDao.selectUserMaxOrderNum();
    }

    @Override
    public ResultObj resetPwd(Integer id) {
        try {
            SysUser user = new SysUser();
            user.setId(id);
            user.setSalt(MD5Utils.createUUID());
            user.setPwd(MD5Utils.md5(Constant.DEFAULT_PWD,user.getSalt(),2));
            this.userDao.update(user,null);
            return ResultObj.RESET_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.RESET_ERROR;
        }
    }

    @Override
    public void saveUserRole(Integer uid, Integer[] rids) {
        //根据用户id删除角色表的关系
        roleDao.deleteRoleUserByUid(uid);
        if (null!=rids&&rids.length>0){
            for (Integer rid : rids) {
                this.userDao.saveUserRole(uid,rid);
            }
        }
    }


    @CacheEvict(cacheNames = "SysUserServiceImpl" ,key = "#id")
    @Override
    public boolean removeById(Serializable id) {
        //根据用户id删除角色表的关系
        roleDao.deleteRoleUserByUid(id);
        return super.removeById(id);
    }

    @Cacheable(cacheNames = "SysUserServiceImpl",key = "#id")
    @Override
    public SysUser getById(Serializable id) {
        return super.getById(id);
    }
}